package com.wlz.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wlz
 * @date 2022-11-26  10:36 上午
 */
@Slf4j
public class RestTemF1 {

    private static final String URL = "https://otaapi.bjev.com.cn/tbox-api-b60v/api/fota/f1";

    private static final String URL_Token = "https://fdt-gateway-3rd.yueyequan.cn/public-auth/cvp/oauth2/token";


    public static void main(String[] args) throws IOException {
        String token = sendHttpToken();
        log.info("token = {}", token);
    }


    public static Response sendHttp(String param) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, param);
        Request request = new Request.Builder()
                .url(URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }

    public static String sendHttpToken() throws IOException {

        Map<String,String> params = new HashMap<>();
        params.put("grant_type", "client_credentials");
        params.put("scope", "third.com/scope/admin");
        String param = JSONObject.toJSONString(params);

        Base64.Encoder encoder = Base64.getEncoder();
        String str = "100121:1feb751b32cd493b9553f34f1309782d";
        String encode = encoder.encodeToString(str.getBytes());

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,param);
        Request request = new Request.Builder()
                .url(URL_Token)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + encode)
                .build();
        Response response = client.newCall(request).execute();
//        String responseBody = response.toString().substring(response.toString().indexOf("{"), response.toString().indexOf("}") + 1);
        System.out.println(response.body().toString());
        JSONObject jsonObject = JSONObject.parseObject(response.body().toString());
        return jsonObject.get("access_token").toString();
    }
}
